<script lang="ts" setup>
import { House, ArrowRight } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { ElConfigProvider } from "element-plus";
import zhCn from "element-plus/es/locale/lang/zh-cn";
import { onMounted, reactive, ref } from "vue";
import { ComDate } from "../model/index";
import createAxios from "../request";
import { format } from "date-fns";

const formatDate = (date: Date): string => {
  return format(date, "yyyy-MM-dd");
};

let axios = createAxios();

let calList: Array<ComDate> = [];

let datas = reactive({
  calList: calList,
});

onMounted(() => {
  getData(String(year));
});

// 获取日历信息
const getData = function (selectYear: string) {
  const yearNumber = Number(selectYear);
  axios({
    url: `/getCalendar`,
    method: "GET",
    params: { year: yearNumber },
  })
    .then((res) => {
      //请求成功
      datas.calList = res.data;
      console.log(datas.calList);

      // 初始化 calendarData
      console.log(111111);
      initCalendarDataFromCalList(datas.calList);
      console.log(calendarData.value);
      ElMessage.success("请求日历数据成功");
    })
    .catch((err) => {
      //请求失败
      ElMessage.error("请求日历数据失败");
    });
};

// 更新日历信息
const updateCalendar = function (updatedDate: ComDate) {
  if (updatedDate.date_type) {
    const dateStr = formatDate(updatedDate.date);
    axios({
      url: `/updateCalendar`,
      method: "POST",
      data: {
        date: dateStr,
        date_type: updatedDate.date_type,
      },
    })
      .then((res) => {
        //请求成功
        console.log(updatedDate);
        if(res.data == 0){
          ElMessage.error("该日期不存在");
        }else if(res.data == 1){
          ElMessage.success("更新日历数据成功");
        }else{
          ElMessage.error("未知错误");
        }
      })
      .catch((err) => {
        //请求失败
        ElMessage.error("更新日历数据失败");
      });
  }
};

const options = [
  { value: 1, label: "工作日" },
  { value: 2, label: "休息日" },
  { value: 3, label: "法定假日" },
  { value: 4, label: "法定调休日" },
];

// 根据当前年份生成选项
let currentDate = new Date();
let year = currentDate.getFullYear();
const value = ref("");
const years = [
  {
    value: year,
    label: year,
  },
  {
    value: year + 1,
    label: year + 1,
  },
  {
    value: year + 2,
    label: year + 2,
  },
  {
    value: year + 3,
    label: year + 3,
  },
  {
    value: year + 4,
    label: year + 4,
  },
];

let yearchange = function (value: string) {
  getData(value);
  // 设置 calendarDate 为该年度的01-01，便于日历重定向到选择的年度
  calendarDate.value = new Date(Number(value), 0, 1);
};

// 日历绑定的日期
const calendarDate = ref(new Date());

// calendarData 的类型定义为一个响应式的 Record<string, string> 对象
const calendarData = ref<Record<string, number>>({});

// 这个函数接受一个 ComDate 对象的数组，并初始化 calendarData
const initCalendarDataFromCalList = (calList: ComDate[]) => {
  // 清空现有的 calendarData
  // calendarData.value = {};

  // 遍历 calList 数组，并填充 calendarData
  calList.forEach((item) => {
    if (item.date && item.date_type) {
      // 将 date 转换为 YYYY-MM-DD 格式的字符串作为键
      const dateStr = formatDate(item.date);
      // 将 date_type 作为值
      calendarData.value[dateStr] = item.date_type;
    } else {
      console.error("获取到不合法数据：", item);
    }
  });
};

const handleChange = (value: string, date: string) => {
  const updatedDate = new ComDate(new Date(date), Number(value));
  updateCalendar(updatedDate);
};

const findDateType = (dateStr: string): number | undefined => {
  return calendarData.value[dateStr];
};
</script>

<template>
  <el-container id="mainView">
    <el-header
      style="
        background-color: #272822;
        color: #e5e5e5;
        line-height: 60px;
        font-size: 27px;
      "
      >日历设定</el-header
    >
    <el-footer
      style="
        height: 30px;
        line-height: 30px;
        background-color: #4e5246;
        border-bottom: 1px solid #7a7a7a;
        border-top: 1px solid #7a7a7a;
      "
    >
      <el-breadcrumb :separator-icon="ArrowRight" style="line-height: 30px">
        <el-breadcrumb-item :to="{ path: '/home/homepage' }"
          ><el-icon><House /></el-icon>首页</el-breadcrumb-item
        >
        <el-breadcrumb-item>时间管理</el-breadcrumb-item>
        <el-breadcrumb-item>日历设定</el-breadcrumb-item>
      </el-breadcrumb>
    </el-footer>
    <el-main style="padding-bottom: 0%">
      <el-select
        v-model="value"
        placeholder="请选择年度"
        size="large"
        style="width: 200px; margin-bottom: 10px; background-color: #1d1e1f"
        @change="yearchange(value)"
      >
        <el-option
          v-for="item in years"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-config-provider :locale="zhCn">
        <el-calendar
          v-model="calendarDate"
          style="background-color: #1d1e1f; color: #e5e5e5"
        >
          <template #date-cell="{ data }">
            <div class="date-cell">
              <p :class="['date-text', data.isSelected ? 'is-selected' : '']">
                {{ data.day.split("-").slice(1).join("-") }}
                {{ data.isSelected ? "✔️" : "" }}
              </p>
              <el-tag
                v-if="findDateType(formatDate(new Date(data.date))) === 1"
                type="info"
                class="tag"
              >
                工作日
              </el-tag>
              <el-tag
                v-else-if="findDateType(formatDate(new Date(data.date))) === 2"
                type="success"
                class="tag"
              >
                休息日
              </el-tag>
              <el-tag
                v-else-if="findDateType(formatDate(new Date(data.date))) === 3"
                type="warning"
                class="tag"
              >
                法定假日
              </el-tag>
              <el-tag
                v-else-if="findDateType(formatDate(new Date(data.date))) === 4"
                type="danger"
                class="tag"
              >
                法定调休日
              </el-tag>
              <el-tag
                v-else-if="findDateType(formatDate(new Date(data.date))) === undefined"
                type="info"
                class="tag"
              >
                未设置
              </el-tag>
              <el-select
                v-if="data.isSelected"
                v-model="calendarData[formatDate(new Date(data.date))]"
                size="small"
                @change="(val: string) => handleChange(val, formatDate(new Date(data.date)))"
                class="date-selector"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>
          </template>
        </el-calendar>
      </el-config-provider>
    </el-main>
  </el-container>
</template>

<style scoped>
#mainView {
  height: 100%;
  width: 100%;
}

.form_item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}

.is-selected {
  color: #1989fa;
}

.date-cell {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  position: relative;
}

.date-text {
  margin: 0;
  font-size: 14px;
  color: #e5e5e5;
  text-align: center;
  position: relative;
}

.date-text:hover {
  cursor: pointer;
  color: #1989fa;
}

.selected-indicator {
  position: absolute;
  top: 0;
  right: 0;
  font-size: 12px;
  color: #1989fa;
}

.tag {
  margin-top: 4px;
  font-size: 12px;
}

.date-selector {
  margin-top: 4px;
  width: 100%;
  max-width: 100px;
}
</style>
